package com.order.web.action;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.order.domain.Customer;
import com.order.domain.User;
import com.order.service.IUserService;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 用户的动作类
 * 
 * @author zhy
 *
 */
@Controller("userAction")
@Scope("prototype")
@ParentPackage("struts-default") // struts-default crm
@Namespace("/user")
@Results({
		// @Result(name = "loginsuccess", type = "dispatcher", location = "/index.jsp"),
		@Result(name = "loginerror", location = "/login.jsp"),
		@Result(name = "json", type = "dispatcher", location = "/login1.jsp"),
		@Result(name = "listUser", type = "redirectAction", location = "findAllUser"),
		@Result(name = "findAll", type = "dispatcher", location = "/jsp/user/userlist.jsp"),
		@Result(name = "addUI", type = "dispatcher", location = "/jsp/user/useradd.jsp"),
		@Result(name = "editUI", type = "dispatcher", location = "/jsp/user/useredit.jsp"),
		@Result(name = "loginout", type = "dispatcher", location = "/login.jsp"),
		@Result(name = "pwdeditsuccess", type = "dispatcher", location = "/pwdseccess.jsp"),
		@Result(name = "authorityError", type = "dispatcher", location = "/authority.jsp"),
		@Result(name = "editError", type = "redirectAction", location = "findAllUser") 
})
public class UserAction extends ActionSupport implements ModelDriven<User>, ServletResponseAware, ServletRequestAware {

	private static final long serialVersionUID = 1L;
	private User user = new User();
	private List<User> users;

	String jsonStr;

	private HttpServletResponse response;
	private HttpServletRequest request;
	
	// 批量删除id
	private String checkTnum;

	@Resource(name = "userService")
	private IUserService userService;

	@Override
	public User getModel() {
		// System.out.println("模型驱动调用getModel方法："+customer.hashCode());
		return user;
	}

	/**
	 * 编辑用户
	 * 
	 * @return
	 */
	@Action("editUser")
	public String editUser() {

		User u = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Integer id = u.getUserId();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonUser;

		if (user.getUserId() == null) {
			map.put("ok", false);
			map.put("err", "请选择要修改的用户");

			jsonUser = JSONObject.fromObject(map);
			jsonStr = jsonUser.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		} else if (user.getUserName() == null || user.getUserName().trim().equals("")) {
			map.put("ok", false);
			map.put("err", "用户名不能为空！");

			jsonUser = JSONObject.fromObject(map);
			jsonStr = jsonUser.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		} else if (user.getPassword() == null || user.getPassword().trim().equals("")) {
			map.put("ok", false);
			map.put("err", "密码不能为空！");

			jsonUser = JSONObject.fromObject(map);
			jsonStr = jsonUser.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		if (id == 1) {

			userService.updateUser(user);
			map.put("ok", true);
		} else {
			map.put("ok", false);
			map.put("err", "无权操作！");
		}

		jsonUser = JSONObject.fromObject(map);
		jsonStr = jsonUser.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listUser";
	}

	/**
	 * 获取编辑用户页面
	 * 
	 * @return
	 */
	@Action("editUIUser")
	public String editUIUser() {

		User uer = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Integer id = uer.getUserId();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonUser;

		if (user.getUserId() == null) {
			map.put("ok", false);
			map.put("err", "请选择要修改的用户");

			jsonUser = JSONObject.fromObject(map);
			jsonStr = jsonUser.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		if (id == 1) {
			// 根据id查询要编辑的用户信息
			User u = userService.findUserById(user.getUserId());

			// 公海账户无法修改
			if (user.getUserId() == null) {

				map.put("ok", false);
				map.put("err", "请选择要修改的用户");

				jsonUser = JSONObject.fromObject(map);
				jsonStr = jsonUser.toString();

			} else if (u.getUserId() == 0) {

				map.put("ok", false);
				map.put("editUser", "公海账户无法修改");

				jsonUser = JSONObject.fromObject(map);
				jsonStr = jsonUser.toString();

			} else {

				map.put("userId", u.getUserId());
				map.put("userName", u.getUserName());
				map.put("password", u.getPassword());

				JSONObject jsonObject = JSONObject.fromObject(map);
				String userStr = jsonObject.toString();

				jsonStr = "{\"ok\": true,\r\n" + "\"user\": " + userStr + "}";

				// 把查询出来的对象压入栈顶
				ActionContext.getContext().getValueStack().push(u);
			}

		} else {
			map.put("ok", false);
			map.put("err", "无权操作！");

			jsonUser = JSONObject.fromObject(map);
			jsonStr = jsonUser.toString();

		}

		// 添加response响应头
		crossDomain();
		// return "editError";
		return "json";
	}

	/**
	 * 删除用户
	 * 
	 * @return
	 */
	@Action("removeUser")
	public String removeUser() {

		User u = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Integer id = u.getUserId();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonUser;

		if (user.getUserId() == null) {
			map.put("ok", false);
			map.put("err", "请选择要删除的用户");

			jsonUser = JSONObject.fromObject(map);
			jsonStr = jsonUser.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}

		if (id == 1) {

			if (user.getUserId() == 0) {
				map.put("ok", false);
				map.put("err", "公海账户无法删除！");
			} else if (user.getUserId() == 1) {
				map.put("ok", false);
				map.put("err", "管理员账户无法删除！");
			} else {
				userService.removeUser(user.getUserId());
				map.put("ok", true);
			}
		} else {

			map.put("ok", false);
			map.put("err", "无权操作！");
		}

		jsonUser = JSONObject.fromObject(map);
		jsonStr = jsonUser.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listUser";
	}
	
	/**
	 * 批量删除
	 * 
	 * @return
	 */
	@Action("deleteAllUser")
	public String deleteAllUser() {
		String strCheckTnum = getCheckTnum();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonCustomer;

		if (strCheckTnum == null || strCheckTnum.trim().equals("")) {
			map.put("ok", false);
			map.put("err", "请选择要删除的用户！");

			jsonCustomer = JSONObject.fromObject(map);
			jsonStr = jsonCustomer.toString();

			// 添加response响应头
			crossDomain();
			return "json";
		}
		
		
		User u = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Integer id = u.getUserId();
		
		if (id == 1) {
			
			String[] checkedNums = strCheckTnum.split(",");
			int n = checkedNums.length;
			int[] checked = new int[n];
			int flag = 0;

			for (int i = 0; i < n; i++) {

				checked[i] = Integer.parseInt(checkedNums[i]);
				
				if (checked[i] == 0) {
					map.put("err", "公海账户无法删除！");
					flag = 1;
					break;
					
				} else if (checked[i] == 1) {
					map.put("err", "管理员账户无法删除！");
					flag = 1;
					break;
					
				} else {
					userService.removeUser(checked[i]);
				}
			}

			if(flag == 0) {				
				map.put("ok", true);
			}else {
				map.put("ok", false);
			}

		} else {
			map.put("ok", false);
			map.put("err", "无权操作！");
		}

		jsonCustomer = JSONObject.fromObject(map);
		jsonStr = jsonCustomer.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listCustomer";
	}

	/**
	 * 新增用户
	 * 
	 * @return
	 */
	@Action("addUser")
	public String addUser() {

		User u = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Integer id = u.getUserId();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonUser;

		if (id == 1) {
			if (user.getUserName().trim().equals("") || user.getUserName() == null) {
				map.put("ok", false);
				map.put("err", "用户名不能为空！");
			} else if (user.getPassword().trim().equals("") || user.getPassword() == null) {
				map.put("ok", false);
				map.put("err", "密码不能为空！");
			} else {
				// 保存用户
				userService.saveUser(user);
				map.put("ok", true);
			}

		} else {
			map.put("ok", false);
			map.put("err", "无权操作！");
		}

		jsonUser = JSONObject.fromObject(map);
		jsonStr = jsonUser.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "listUser";
	}

	/**
	 * 查询用户列表
	 * 
	 * @return
	 */
	@Action("findAllUser")
	public String findAllUser() {

		User u = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		Integer id = u.getUserId();

		Map<String, Object> userMap = new HashMap<String, Object>();
		JSONObject jsonUser;

		if (id == 1) {
			// 定义离线对象
			DetachedCriteria uCriteria = DetachedCriteria.forClass(User.class);

			// 根据离线对象查询客户信息
			users = userService.findAllUser(uCriteria);

			// 更新学生数量
			for (User o : users) {
				Integer uId = o.getUserId();

				DetachedCriteria dCriteria = DetachedCriteria.forClass(Customer.class);
				userService.updateStudentNum(dCriteria, uId);
			}

			List<User> uer = userService.findAllUser(uCriteria);

			int j = uer.size();
			String[] uers = new String[j - 1];

			if (uer != null) {

				for (int i = 1; i < j; i++) {

					Map<String, Object> map = new HashMap<String, Object>();

					User value = uer.get(i);

					map.put("userId", value.getUserId());
					map.put("userName", value.getUserName());
					map.put("password", value.getPassword());
					map.put("studentNum", value.getStudentNum());

					JSONObject jsonObject = JSONObject.fromObject(map);
					uers[i - 1] = jsonObject.toString();
				}

			}

			String str = Arrays.toString(uers);
			jsonStr = "{\"ok\": true,\r\n" + "\"users\": " + str + "}";

			/*
			 * userMap.put("uers", str); userMap.put("ok", true);
			 * 
			 * jsonUser = JSONObject.fromObject(userMap); jsonStr = jsonUser.toString();
			 */

			// 添加response响应头
			crossDomain();
			// return "findAll";
			return "json";
		}

		userMap.put("ok", false);
		userMap.put("uers", "无权访问！");

		jsonUser = JSONObject.fromObject(userMap);
		jsonStr = jsonUser.toString();

		// 添加response响应头
		crossDomain();
		// return "authorityError";
		return "json";
	}

	/**
	 * 获取添加用户页面
	 * 
	 * @return
	 */
	@Action("addUIUser")
	public String addUIUser() {
		return "addUI";
	}

	/**
	 * 用户登录
	 * 
	 * @return
	 */
	@Action("login")
	public String login() {

		User loginUser = userService.findByUserNameAndPwd(user.getUserName(), user.getPassword());
		Map<String, Object> map = new HashMap<String, Object>();

		if (loginUser != null) {
			
			/*Cookie cookie = new Cookie("userName" , loginUser.getUserName());
			cookie.setMaxAge(60*60);
			cookie.setPath("/order");
			
			// 添加response响应头
			crossDomain(cookie);*/
			
			ServletActionContext.getRequest().getSession().setAttribute("user", loginUser);
			
			map.put("ok", true);

			if (loginUser.getUserId() == 1) {
				map.put("isAdmin", true);
			}

			// StringBuffer x = request.getRequestURL();
			/*
			 * String xx; System.out.println("x:"+x);
			 * 
			 * Pattern pattern1 = Pattern.compile("^http://localhost:8080"); Matcher matcher
			 * = pattern1.matcher(x); //System.out.println("matcher:"+matcher);
			 * if(matcher.find()){ System.out.println("---------------------------");
			 * System.out.println("mat:"+matcher.group()); xx = matcher.group();
			 * 
			 * } else { Pattern pattern2 = Pattern.compile(
			 * "^http://((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?[1-9])))(\\:\\d{2,})*)"
			 * ); matcher = pattern2.matcher(x); if(matcher.find()){
			 * System.out.println("---------------------------");
			 * System.out.println("mat:"+matcher.group()); xx = matcher.group(); } }
			 */

			// return "loginsuccess";

		} else {
			map.put("ok", false);
			map.put("err", "用户名或密码错误！");
		}

		// this.addFieldError("msg", "用户名或密码错误！");
		// return "loginerror";

		JSONObject jsonObject = JSONObject.fromObject(map);
		jsonStr = jsonObject.toString();

		// 添加response响应头
		crossDomain();
		// return "loginerror";
		return "json";
	}

	/**
	 * 退出登录
	 * 
	 * @return
	 */
	@Action("loginout")
	public String loginout() {

		// 清空session
		ServletActionContext.getRequest().getSession().invalidate();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ok", true);

		JSONObject jsonObject = JSONObject.fromObject(map);
		jsonStr = jsonObject.toString();

		// 添加response响应头
		crossDomain();
		return "json";
		// return "loginout";
	}

	/**
	 * 修改密码
	 * 
	 * @return
	 */
	@Action("pwdedit")
	public String pwdEdit() {
		User sessionUser = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		sessionUser.setPassword(user.getPassword());
		userService.pwdUpdate(sessionUser);
		ServletActionContext.getRequest().getSession().removeAttribute("user");
		return "pwdeditsuccess";
	}

	/**
	 * 添加response响应头 跨域
	 */
	public void crossDomain(Cookie cookie) {
		String origin = request.getHeader("Origin");

		response.setHeader("Access-Control-Allow-Origin", origin);
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.addCookie(cookie);
	}
	
	/**
	 * 添加response响应头 跨域
	 */
	public void crossDomain() {
		String origin = request.getHeader("Origin");

		response.setHeader("Access-Control-Allow-Origin", origin);
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Allow-Credentials", "true");
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {

		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getJsonStr() {
		return jsonStr;
	}

	public void setJsonStr(String jsonStr) {
		this.jsonStr = jsonStr;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public String getCheckTnum() {
		return checkTnum;
	}

	public void setCheckTnum(String checkTnum) {
		this.checkTnum = checkTnum;
	}

}
